<?php
/**
 * Class AgentAddress
 * Desc  用户地址Controller
 * Create on 2021/8/26 14:56
 * Create by wangyafang
 */

namespace app\api\controller\xyb;

use app\api\model\xyb\UserAddress as UserAddressModel;
use app\api\service\UsersService;
use think\Db;

class UserAddress extends Base
{
    protected $noNeedLogin = [''];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    public function _initialize(){
        parent::_initialize();
        $this->model = new UserAddressModel();
    }

    public function index()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $users = $this->getAuthUsers();
        $where['user_id'] = array('eq', $users->id);
        $data = $this->model->getList($this->model,$where,'id,group_name,group_ids,agent_id,detail,name,mobile,defaults', 'defaults desc');
        $this->success('请求成功',$data);
    }

    /**
     * desc:添加地址
     * param:请求default值:true,false  数据表结果:1,0
     */
    public function add()
    {
        $param = $this->request->param();
        $users = $this->getAuthUsers();
        $default_id = $this->model->where(['user_id'=>$users->id, 'defaults'=>1])->value('id');
        Db::startTrans();
        try{
            if($default_id && $param['defaults']) {
                Db::name('xyb_user_address')->where('user_id',$users->id)->update(['defaults'=>0]);
            }
            Db::name('xyb_user_address')->insert([
                'user_id'=>$users->id,
                'name'=>$param['name'],
                'mobile'=>$param['mobile'],
                'group_name'=>$param['group_name'],
                'group_ids'=>$param['group_ids'],
                'detail'=>$param['detail'],
                'agent_id'  => $param['agent_id'],
                'defaults'=>$param['defaults'] == true ? 1 : 0,
                'createtime'=>time()
            ]);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
        $id = $this->model->where('user_id', $users->id)->order('id desc')->value('id');
        $data = ['id'=>$id];
        $this->success('操作成功',$data);
    }

    public function detail()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $address_id = $this->request->param('id');
        $users = $this->getAuthUsers();
        $address = $this->model->where(['id' => $address_id, 'user_id'=>$users->id])->find();
        $this->success('请求成功',$address);
    }

    /**
     * desc:编辑用户地址
     */
    public function edit()
    {
        $param = $this->request->param();
        $users = $this->getAuthUsers();
        Db::startTrans();
        try{
            if(($param['defaults']) == 'true') {
                Db::name('xyb_user_address')->where('user_id',$users->id)->update(['defaults'=>0]);
            }
            Db::name('xyb_user_address')
                ->where('id',$param['id'])
                ->update([
                    'group_name'=>$param['group_name'],
                    'group_ids'=>$param['group_ids'],
                    'detail'=>$param['detail'],
                    'name'=>$param['name'],
                    'mobile'=>$param['mobile'],
                    'defaults'=>$param['defaults'] == 'true' ? 1 : 0,
                    'updatetime'=>time(),
                ]);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('操作成功');
    }

    /**
     * @desc:删除用户地址
     */
    public function del()
    {
        $userAddressObj = $this->model->get($this->request->param('id'));
        if($userAddressObj && $userAddressObj->defaults){
            $this->error('默认地址不能删除');
        }
        $userAddressObj->delete();
        $this->success('删除成功');
    }

    /**
     * desc:设置默认地址
     */
    public function set_defaults()
    {
        $id = $this->request->param('id');
        $users = $this->getAuthUsers();
        Db::startTrans();
        try{
            Db::name('xyb_user_address')->where('user_id',$users->id)->update(['defaults'=>0]);
            Db::name('xyb_user_address')->where('id',$id)->update(['defaults'=>1]);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('操作成功');
    }

    public function region(){
        $users = $this->getAuthUsers();
        $user_agent = UsersService::getCommunityWhereUsersLocated($users->id);
        $agent_address = UsersService::getUsersCommunityAddressInformation($users->id);
//        $this->success('操作成功', [
//            'id'        => $user_agent['agent_id'],
//            'name'      => $user_agent['agent_area'],
//            'children'  => $agent_address
//        ]);
        $this->success('操作成功', [
            'agent'     => ['agent_id' => $user_agent['agent_id'], 'agent_name' => $user_agent['agent_area']],
            'region'    => $agent_address
        ]);
    }
}